using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DoveSiButta.Helpers;
using DoveSiButta.Models;
using System.IO;

namespace DoveSiButta.Controllers {

    [HandleErrorWithELMAH]
    public class BoxesController : Controller {

        IBoxRepository boxRepository;

        //
        // Dependency Injection enabled constructors

        public BoxesController()
            : this(new BoxRepository()) {
        }

        public BoxesController(IBoxRepository repository) {
            boxRepository = repository;
        }

        //
        // GET: /Boxes/
        //      /Boxes/Page/2
        //      /Boxes?q=term

        public ActionResult Index(string q, int? page) {

            const int pageSize = 25;

            IQueryable<Box> boxes = null;

            //Searching?
            if (!string.IsNullOrWhiteSpace(q))
                boxes = boxRepository.FindBoxesByText(q).OrderByDescending(d => d.EventDate); //2012-05-14 era OrderBy //GM
            else 
                boxes = boxRepository.FindUpcomingEvents();

            var paginatedBoxes = new PaginatedList<Box>(boxes, page ?? 0, pageSize);

            return View(paginatedBoxes);
        }

        //
        // GET: /Boxes/Details/5

        public ActionResult Details(int? id) {
            if (id == null) {
                return new FileNotFoundResult { Message = "No Box found due to invalid box id" };
            }

            Box box = boxRepository.GetBox(id.Value);
            string replaceWith = " ";
            try
            {

                box.Address = box.Address.Replace(Environment.NewLine, " ").Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);//box.Address.Replace('\n', ' ');
                box.Title = box.Title.Replace(Environment.NewLine, " ").Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);//box.Title.Replace('\n', ' ');
            }
            catch (Exception)
            {
            }

            if (box == null) {
                return new FileNotFoundResult { Message = "No Box found for that id" };
            }

            return View(box);
        }

        //
        // GET: /Boxes/Edit/5

        [Authorize]
        public ActionResult Edit(int id) {

            Box box = boxRepository.GetBox(id);

            if (!box.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");

            return View(box);
        }

        //
        // POST: /Boxes/Edit/5

        [HttpPost, Authorize]
        public ActionResult Edit(int id, FormCollection collection) {

            Box box = boxRepository.GetBox(id);

            if (!box.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");

            try {
                UpdateModel(box, "Box");

                boxRepository.Save();

                return RedirectToAction("Details", new { id=box.BoxID });
            }
            catch {
                return View(box);
            }
        }

        //
        // GET: /Boxes/Create

        [Authorize]
        public ActionResult Create() {

            Box box = new Box() {
               EventDate = DateTime.Now.AddDays(7)
            };

            return View(new BoxFormViewModel(box));
        } 

        //
        // POST: /Boxes/Create

        [HttpPost, Authorize]
        public ActionResult Create(Box box) {

            if (ModelState.IsValid) {
                NerdIdentity utente = (NerdIdentity)User.Identity;
                box.HostedById = utente.Name;
                box.HostedBy = utente.FriendlyName;

                Rating rsvp = new Rating();
                rsvp.AttendeeNameId = utente.Name;
                rsvp.AttendeeName = utente.FriendlyName;
                box.Ratings.Add(rsvp);

                //GM 2011-12-09 START

                box.BoxType = Request.Form["Box.BoxType"]; //GM Perche' funziona solo cosi'?

                
                //http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx
                //foreach (string file in Request.Files) 
                //{ HttpPostedFile hpf = Request.Files[file] as HttpPostedFile; 
                //    if (hpf.ContentLength == 0)      
                //        continue; 
                //    string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName)); 
                //    hpf.SaveAs(savedFileName); 
                //}
                //Corretto con http://forums.asp.net/t/546196.aspx

                

                var inputFile = Request.Files["FileUpload"];
                if (inputFile.ContentLength > 0)
                {
                    
                    //byte[] tempPicture = new byte[inputFile.ContentLength];
                    //inputFile.InputStream.Read(tempPicture, 0, inputFile.ContentLength);


                    DateTime time = DateTime.Now;
                    string format = "yyyyMMdd_hhmmss";
                    box.Picture_Filename = time.ToString(format) + System.IO.Path.GetRandomFileName() + ".jpg";
                    //d.Picture_File = encodedDataAsBytes;
                    //Per scrivere su disco
                    string picturesFolder = "Pictures/";
                    string baseAppPath = Request.ApplicationPath; //AppDomain.CurrentDomain.BaseDirectory;// HttpContext.Current.Request.ApplicationPath;
                    string picturesPath = baseAppPath + picturesFolder;
                    string filePath = Path.Combine(Server.MapPath(picturesPath)
                        , box.Picture_Filename);
                    //FileStream fs = new FileStream(filePath, FileMode.Create);
                    //fs.Write(tempPicture, 0, tempPicture.Length);
                    //fs.Close();
                    inputFile.SaveAs(filePath); 

                    Picture pic = new Picture();
                    pic.Picture_Filename = box.Picture_Filename;
                    box.Pictures.Add(pic);

                }
                else
                {
                    box.Picture_Filename = "";
                }
                //GM 2011-12-09 END
                boxRepository.Add(box);
                boxRepository.Save();

                return RedirectToAction("Details", new { id=box.BoxID });
            }

            return View(new BoxFormViewModel(box));
        }

        //
        // HTTP GET: /Boxes/Delete/1

        [Authorize]
        public ActionResult Delete(int id) {

            Box box = boxRepository.GetBox(id);

            if (box == null)
                return View("NotFound");

            if (!box.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");

            return View(box);
        }

        // 
        // HTTP POST: /Boxes/Delete/1

        [HttpPost, Authorize]
        public ActionResult Delete(int id, string confirmButton) {

            Box box = boxRepository.GetBox(id);

            if (box == null)
                return View("NotFound");

            if (!box.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");

            boxRepository.Delete(box);
            boxRepository.Save();

            return View("Deleted");
        }

  
        protected override void HandleUnknownAction(string actionName)
        {
            throw new HttpException(404, "Action not found");
        }

        public ActionResult Confused()
        {
            return View();
        }

        public ActionResult Trouble()
        {
            return View("Error");
        }

        [Authorize]
        public ActionResult My()
        {

            NerdIdentity nerd = (NerdIdentity)User.Identity;
            var userBoxes = from box in boxRepository.FindAllBoxes()
                              where
                                (
                                String.Equals((box.HostedById ?? box.HostedBy), nerd.Name)
                                    ||
                                box.Ratings.Any(r => r.AttendeeNameId == nerd.Name || (r.AttendeeNameId == null && r.AttendeeName == nerd.Name)) 
                                )
                              orderby box.EventDate descending //GM 2012-05-15 aggiunto descending
                              select box;

            return View(userBoxes);
        }

        public ActionResult WebSlicePopular()
        {
            ViewData["Title"] = "Elementi popolari";
            var model = from box in boxRepository.FindUpcomingEvents()
                                        orderby box.Ratings.Count, box.EventDate descending
                                        select box;
            return View("WebSlice",model.Take(5));
        }

        public ActionResult WebSliceUpcoming()
        {
            ViewData["Title"] = "Prossimi eventi";
            DateTime d = DateTime.Now.AddMonths(1);
            var model = from box in boxRepository.FindUpcomingEvents()
                        where box.EventDate < d
                        orderby box.EventDate descending
                    select box;
            return View("WebSlice", model.Take(5));
        }

    }
}